package com.qinglei.recoup.system.task;

import com.qinglei.recoup.common.domain.CommonConstant;
import com.qinglei.recoup.common.domain.RadarVersionEnum;
import com.qinglei.recoup.common.exception.RedisConnectException;
import com.qinglei.recoup.common.service.RedisService;
import com.qinglei.recoup.common.utils.JsonUtils;
import com.qinglei.recoup.system.domain.Bed;
import com.qinglei.recoup.system.domain.BedRadarBO;
import com.qinglei.recoup.system.domain.Event;
import com.qinglei.recoup.system.manager.BreathHeartAlarmV3;
import com.qinglei.recoup.system.manager.BreathHeartAlarmV4;
import com.qinglei.recoup.system.manager.BreathHeartAlarmV7;
import com.qinglei.recoup.system.pojo.BedMonitorTimeVO;
import com.qinglei.recoup.system.service.BedService;
import com.qinglei.recoup.system.service.RadarUserDataService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Set;

/**
 * 处理床位相关定时任务
 */
@Slf4j
@Component
public class BedTask {

    @Autowired
    private RedisService redisService;

    @Resource
    private BedService bedService;

    @Resource
    private BreathHeartAlarmV3 breathHeartAlarmV3;

    @Resource
    private BreathHeartAlarmV4 breathHeartAlarmV4;

    @Resource
    private BreathHeartAlarmV7 breathHeartAlarmV7;

    public void checkOutBedTimeout() {
        log.info("checkOutBedTimeout run");
        try {
            long expire = System.currentTimeMillis() / 1000;
            Set<String> bedIds = redisService.zrangeByScore(CommonConstant.OUT_BED_ZSET_PREFIX, "-inf", String.valueOf(expire));
            if (CollectionUtils.isNotEmpty(bedIds)) {
                log.info("out bed timeout bedIds:{}", bedIds);
                bedIds.forEach(bedId -> {
                    try {
                        Event event = new Event();
                        event.setBedId(Integer.valueOf(bedId));
                        event.setHappenTime(LocalDateTime.now());
                        event.setType(Bed.SUB_STATUS_OUT_BED_TOO_LONG);
                        bedService.procAlarmEvent(event,Bed.SUB_STATUS_OUT_BED_TOO_LONG);
                        BedRadarBO bedRadarBO = bedService.getBedWithSn(Integer.valueOf(bedId));
                        if(RadarVersionEnum.VERSION_V4.getCode().equals(bedRadarBO.getRadarVersion())){
                            breathHeartAlarmV4.clearAlearm(Integer.valueOf(bedId));
                        }else if(RadarVersionEnum.VERSION_V3.getCode().equals(bedRadarBO.getRadarVersion())){
                            breathHeartAlarmV3.clearAlearm(Integer.valueOf(bedId));
                        }else if(RadarVersionEnum.VERSION_V7.getCode().equals(bedRadarBO.getRadarVersion())){
                            breathHeartAlarmV7.clearAlearm(Integer.valueOf(bedId));
                        }
                    } catch (Exception e) {
                        log.error("checkOutBedTimeout error bedId:{}", bedId, e);
                    }
                });
                redisService.zrem(CommonConstant.OUT_BED_ZSET_PREFIX, bedIds.toArray(new String[bedIds.size()]));
            }
        } catch (RedisConnectException e) {
            log.error("checkOutBedTimeout error", e);
        }
    }

    public void checkBedMonitorTime() {
        log.info("checkBedMonitorTime run");
        try {
            long expire = System.currentTimeMillis() / 1000;
            // 检查已经结束的监测时间段
            Set<String> endMonitorTimes = redisService.zrangeByScore(CommonConstant.BED_MONITOR_TIME_END_ZSET_PREFIX,
                    "-inf", String.valueOf(expire));
            if (CollectionUtils.isNotEmpty(endMonitorTimes)) {
                endMonitorTimes.forEach(timeStr -> {
                    try {
                        BedMonitorTimeVO bedMonitorTimeVO = JsonUtils.jsonToBean(timeStr, BedMonitorTimeVO.class);
                        bedService.procBedMonitorTimeEnd(bedMonitorTimeVO);
                    } catch (Exception e) {
                        log.error("checkBedMonitorTime end error", e);
                    }
                });
            }
            // 检查已经开始的监测时间段
            Set<String> startMonitorTimes = redisService.zrangeByScore(CommonConstant.BED_MONITOR_TIME_START_ZSET_PREFIX,
                    "-inf", String.valueOf(expire));
            if (CollectionUtils.isNotEmpty(startMonitorTimes)) {
                startMonitorTimes.forEach(timeStr -> {
                    try {
                        BedMonitorTimeVO bedMonitorTimeVO = JsonUtils.jsonToBean(timeStr, BedMonitorTimeVO.class);
                        bedService.procBedMonitorTimeStart(bedMonitorTimeVO);
                    } catch (Exception e) {
                        log.error("checkBedMonitorTime start error", e);
                    }
                });
            }
        } catch (Exception e) {
            log.error("checkBedMonitorTime error", e);
        }
    }

}
